package com.woniu.admin.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.woniu.admin.vo.AjaxResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/getVerifyCodeImage")
    public AjaxResult getVerifyCodeImage(HttpServletResponse response) throws IOException {
        //1. 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        captcha.setGenerator(randomGenerator);
        //2. 重新生成code
        captcha.createCode();
        String code = captcha.getCode();
        System.out.println(code);
        //3. 保存验证码
        String uuid = IdUtil.randomUUID().toUpperCase().replace("-", "");
        redisTemplate.opsForValue().set(uuid, code);
        //4. 返回给前台页面
        String imageBase64Data = captcha.getImageBase64Data();
        System.out.println(imageBase64Data);
        AjaxResult ajaxResult = AjaxResult.success("生成验证码成功", imageBase64Data);
        ajaxResult.put("uuid", uuid);
        return ajaxResult;
    }
}